package com.tristia.resources.impl;

import java.util.List;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.tristia.entity.Book;
import com.tristia.entity.Books;
import com.tristia.entity.SuccessInfo;
import com.tristia.resources.BookResource;
import com.tristia.service.BookService;

@Component
@Path("/old/books")
@Scope("request")
public class BookResourceWs implements BookResource {
	@Autowired
	BookService bookService;
	@Context 
	UriInfo ui;
	private Logger log = Logger.getLogger(this.getClass());
	private Books books = new Books();

/*	@GET
	@Produces("application/json")
	public String getBooks() {
		log.info("getBooks entered");

		StringBuffer jsonBuffer = new StringBuffer("{ \"Books\": [");
		List<Book> books = bookService.getAll();
		boolean first = true;
		for (Book book : books) {
			if (first)
				first = false;
			else
				jsonBuffer.append(",");
			jsonBuffer.append(getJsonBookObject(book));
		}
		jsonBuffer.append("]}");
		log.info("Sending: \n\n" + jsonBuffer.toString() + "\n\n");
		return jsonBuffer.toString();
	}*/
	
	@GET
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML })
	public Books getBooks() {
		log.info("getBooks entered");
		books.getBooks().addAll(bookService.getAll());
		log.info("Got books in DB");
		log.info("Sending: \n\n" + books.toString() + "\n\n");
		return books;
	}

/*	@GET
	@Path("/{id}")
//	@Produces("application/json")
	@Produces("application/xml")
	public Book getBook(@PathParam("id") String id) {
		log.info("getBook entered");
		log.info("Hit getBook");
		Book book = bookService.getById(Integer.parseInt(id));
		log.info("Sending: \n\n" + book + "\n\n");
		return book;
	}*/
	@GET
	@Path("/{id}")
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML })
	public Book getBook(@PathParam("id") String id) {
		log.info("getBook entered");
		log.info("Hit getBook");
		Book book = bookService.getById(Integer.parseInt(id));
		log.info("Got book in DB");
		log.info("Sending: \n\n" + book.toString() + "\n\n");
		return book;
	}

/*	@PUT
	@Produces("text/plain")
	public String updateBook(@QueryParam("id") String id,
			@QueryParam("title") String title, @QueryParam("author") String author) {
		log.info("updateBook entered");
		log.info("title: " + title);
		log.info("author : " + author);
		log.info("id : " + id);

		if (StringUtils.hasText(id)) {
			log.info("It has an ID");
			int idd = Integer.parseInt(id);
			Book book = bookService.getById(idd);
			if (book != null) {
				log.info("We found the book with that id");
				book.setTitle(author);
				book.setAuthor(title);
				bookService.update(book);
			}
		} else {
			Book book = new Book();
			book.setTitle(title);
			book.setAuthor(author);
			bookService.save(book);
		}
		return "nothing";
	}*/
	
	@PUT
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML })
	public SuccessInfo updateBook(@QueryParam("id") String id,
			@QueryParam("title") String title,
			@QueryParam("author") String author) {
		log.info("updateBook entered");
		log.info("title: " + title);
		log.info("author : " + author);
		log.info("id : " + id);
		
		SuccessInfo successInfo = new SuccessInfo();
		if (StringUtils.hasText(id)) {
			log.info("It has an ID");
			long idd = Long.parseLong(id);
			Book book = bookService.getById(idd);
			if (book != null) {
				log.info("We found the book with that id");
				book.setTitle(title);
				book.setAuthor(author);
				bookService.update(book);
				log.info("Updated book in DB");
				successInfo.getSuccesses().add("Updated successfully");
			} else {
				log.info("We do not found the book with that id");
				//errorInfo
			}
		} else {
			log.info("It has not an ID");
			log.info("Put the new book");
			Book book = new Book();
			book.setTitle(title);
			book.setAuthor(author);
			bookService.save(book);
			log.info("Saved book in DB");
			successInfo.getSuccesses().add("Created successfully");
		}
		return successInfo;
	}

/*	@POST
	@Produces("text/plain")
	public String addBook(@QueryParam("title") String title,
			@QueryParam("author") String author) {
		log.info("addBook entered");

		log.info("title: " + title);
		log.info("author : " + author);

		Book book = new Book();
		book.setTitle(title);
		book.setAuthor(author);
		bookService.save(book);
		return "nothing";
	}*/
	
	@POST
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML })
	public SuccessInfo addBook(@QueryParam("title") String title,
			@QueryParam("author") String author) {
		log.info("addBook entered");
		log.info("title: " + title);
		log.info("author : " + author);

		SuccessInfo successInfo = new SuccessInfo();
		Book book = new Book();
		book.setTitle(title);
		book.setAuthor(author);
		bookService.save(book);
		log.info("Saved book in DB");
		successInfo.getSuccesses().add("Created successfully");
		return successInfo;
	}

/*	@DELETE
	@Path("/{id}")
	@Produces("text/plain")
	public String deleteBook(@PathParam("id") String id) {
		log.info("deleteBook entered");
		log.info("id : " + id);
		if(id!=null) {
			deleteBookById(id);
		}
		
		MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
		List<String> ids = queryParams.get("id");
		if(ids == null) {
			log.info("\n\nThe ids is null");
		} else {
			for (String currentid : ids) {
				deleteBookById(currentid);
			}
		}
		return "success";
	}

	private void deleteBookById(String id) {
		log.info("Delete Id: " + id);
		Book book = bookService.getById(Integer.parseInt(id));
		if (book == null) {
			log.info("Null was returned for ID: " + id);
		} else {
			bookService.delete(book);
			log.info("Deleted book in DB");
		}
	}*/
	
	@DELETE
	@Path("/{id}")
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_XML })
	public SuccessInfo deleteBook(@PathParam("id") String id) {
		log.info("deleteBook entered");
		log.info("id : " + id);
		
		SuccessInfo successInfo = new SuccessInfo();
		if(id!=null) {
			deleteBookById(id);
			successInfo.getSuccesses().add("Deleted successfully");
		}
		
		MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
		List<String> ids = queryParams.get("id");
		if(ids == null) {
			log.info("\n\nThe ids is null");
		} else {
			for (String currentid : ids) {
				deleteBookById(currentid);
				successInfo.getSuccesses().add("Deleted successfully");
			}
		}
		return successInfo;
	}

	private void deleteBookById(String id) {
		log.info("Delete Id: " + id);
		Book book = bookService.getById(Integer.parseInt(id));
		if (book == null) {
			log.info("Null was returned for ID: " + id);
		} else {
			bookService.delete(book);
			log.info("Deleted book in DB");
			//successInfo
		}
	}

/*	private Object getJsonBookObject(Book book) {
		StringBuffer buffer = new StringBuffer("{\"id\": " + book.getId());
		buffer.append(",\"title\": \"").append(book.getTitle());
		buffer.append("\",\"author\": ").append(book.getAuthor());
		buffer.append("}");
		return buffer.toString();
	}*/
}
